package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
@Slf4j
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper,ApReadBehavior> implements ApReadBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private ApReadBehaviorMapper apReadBehaviorMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = ApThreadLocalUtils.getUser();
        Integer userId = null;
        if(apUser.getId()!=null && apUser.getId()>0){
            userId = apUser.getId();
        }

        //2.查询行为实体判断是否存在
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdAndEquipmentId(userId, dto.getEquipmentId());
        if(apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体不存在");
        }

        //3.查询阅读行为数据
        ApReadBehavior apReadBehavior = getOne(Wrappers.<ApReadBehavior>lambdaQuery()
                .eq(ApReadBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApReadBehavior::getArticleId, dto.getArticleId())
        );

        //4.判断阅读行为数据如果不存在就创建
        if(apReadBehavior==null){
            apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(apBehaviorEntry.getId());//行为实体ID
            apReadBehavior.setArticleId(dto.getArticleId());//文章ID
            apReadBehavior.setCount((short)1); //阅读次数
            apReadBehavior.setLoadDuration(dto.getLoadDuration());//加载时长
            apReadBehavior.setPercentage(dto.getPercentage());//阅读百分比
            apReadBehavior.setReadDuration(dto.getReadDuration());//阅读时长
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());

            save(apReadBehavior);
        } else {
            //5.如果存在就更新
//            ApReadBehavior apReadBehaviorDB = new ApReadBehavior();
//            apReadBehaviorDB.setId(apReadBehavior.getId());
//            apReadBehaviorDB.setCount((short)(apReadBehavior.getCount()+1));
//            updateById(apReadBehaviorDB);

            //调用数据库原子自增操作（线程安全的），更新阅读次数累加1
            apReadBehaviorMapper.updateCountById(apReadBehavior.getId());
        }


        //生产本次阅读数据到kafka
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId()); //文章ID
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS); //阅读类型

        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
